import React from 'react';
import { connect, routerRedux } from 'dva';
import { Layout, Card, Input, Button, Row, Col, message} from 'antd';
import { Form } from '@ant-design/compatible';
import { PlusOutlined } from '@ant-design/icons'
import BaseComponent from 'components/BaseComponent';
import './index.less';
const { Content } = Layout;
import { addCourseware } from '../../CoursewareManage/service'

const { TextArea } = Input;
const createForm = Form.create;
@connect(({ courseware }) => ({
  courseware
}))
class AddCourseware extends BaseComponent {
  constructor (props) {
    super(props)

    this.state = {
      name: '',
      pages: [{idx: 1, title: '', content: ''}]
    }
  }

  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const name = values.name
        const pages = this.state.pages
        const temp = []

        pages.map((item, index) => {
          const t = {}
          index = index + 1
          t.idx = values['idx_' + index]
          t.title = values['title_' + index]
          t.content = values['content_' + index]
          t.creator = 1
          t.updater = 1
          temp.push(t)
        })
        const payload = {
          'name': name, 
          'creator': 1,
          'updater': 1,
          'pages': temp}
        addCourseware(payload).then(resp => {
          if (resp && resp.status) {
            message.success('发布成功')
            window.location.replace("/")
          } else {
            message.error('发布失败')
          }
        }).catch(err => {
          console.log('发布失败:', err)
        })
      }
    })
  }

  addPage = () => {
    const pages = this.state.pages
    if(pages && pages.length >= 5) {
      message.warn('最多添加五张幻灯片')
      return
    }
    const pageTemp = {
      idx: pages && pages.length > 0 ? parseInt(pages.length) + parseInt(1) : 1,
      title: '',
      content: ''
    }
    pages.push(pageTemp)
    this.setState({
      pages: pages
    })
  }

  delPage = (idx) => {
    const pages = this.state.pages
    if(pages && pages.length <= 1) {
      message.warn('至少保留一张幻灯片')
      return
    }
    pages.forEach((item,index,pages) => {
      if(parseInt(index)+1 === idx){
        pages.splice(index,1)
      }
    })  
    this.setState({
      pages: pages
    })
  }
  

  render() {
    const { form } = this.props
    const { pages, name } = this.state
    const { getFieldDecorator } = form

    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
    }

    return(
      <Layout className="full-layout page editcourseware-page">
        <Content>
          <Form
            {...formItemLayout}
            layout={'horizontal'}
            onSubmit={this.handleSubmit}
          >
            <Card>
              <Row>
                <Col span={20}>
                  <Form.Item label={'名称'} >
                    {getFieldDecorator('name', {initialValue: name || ''})(<Input placeholder='课件名称' />) }
                  </Form.Item>
                </Col>
                <Col span={4}>
                  
                </Col>
              </Row>
              
            </Card>
            {
              pages.map((item, idx) => {
                idx = idx+1
                return(
                    <Card key={idx}>
                      <Row>
                        <Col span={20}>
                      <Form.Item 
                        style={{display: 'none'}}
                      >
                        {getFieldDecorator('idx_' + idx, {initialValue: idx || 0})(<Input />) }
                      </Form.Item>
                      <Form.Item label={'幻灯片'+idx+'标题'} 
                        style={{paddingBottom: '20px'}}
                        rules={[
                          {
                            required: true,
                            message: '幻灯片标题必填!',
                          },
                        ]}
                      >
                        {getFieldDecorator('title_' + idx, {initialValue:item.title || ''})(<Input placeholder='标题' />) }
                      </Form.Item>
                      <Form.Item label={'幻灯片'+idx+'内容'}
                        rules={[
                          {
                            required: true,
                            message: '幻灯片内容必填!',
                          },
                        ]}
                      >
                        {getFieldDecorator('content_' + idx, {initialValue:item.content || ''})(<TextArea rows={4} placeholder='内容' />) }
                      </Form.Item>
                      </Col>
                      <Col span={4}>
                        <Button
                          size="large"
                          type="primary"
                          className="login-form-button"
                          onClick={this.delPage.bind(this, idx)}
                        >
                          删除幻灯片
                        </Button>
                      </Col>
                      </Row>
                    </Card>
                )
              })
            }
            <Card>
              <Button
                size="large"
                type="dashed"
                block 
                className="login-form-button"
                onClick={this.addPage}
                style={{marginBottom: '20px'}}
                icon={<PlusOutlined/>}
              >
                添加幻灯片
              </Button>
              
              <Form.Item>
                <Button
                  size="large"
                  type="primary"
                  htmlType="submit"
                  className="login-form-button"
                >
                  发布
                </Button>
              </Form.Item>
            </Card>
          </Form>
        </Content>
      </Layout>
    )
  }
}

export default createForm()(AddCourseware);
